package pwd.allen.androiddemo.activity;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import pwd.allen.androiddemo.R;
import pwd.allen.androiddemo.util.CheckNotifyPermissionUtils;

/**
 * 系统通知
 * 需要添加授权：<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/> <!-- 允许发布通知 -->
 * 手机打开允许通知（悬浮通知、锁屏通知、常驻通知、桌面图标角标）
 */
public class NotificationActivity extends AppCompatActivity implements View.OnClickListener {

    private final static String IMPORTANT_CHANNEL_ID = "notification_pwd";
    private NotificationManager notificationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification);

        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);

        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        boolean enabled = notificationManager.areNotificationsEnabled();
        if (!CheckNotifyPermissionUtils.checkNotifyPermission(this)) {
            // 通知权限未被授权，跳转至通知权限设置页面
            CheckNotifyPermissionUtils.tryJumpNotifyPage(this);
        }

        // android8之后支持设置通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(IMPORTANT_CHANNEL_ID,
                    "重要通知", NotificationManager.IMPORTANCE_HIGH);
            channel.setDescription("这是重要通知，建议开启");
            notificationManager.createNotificationChannel(channel);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent(this, NotificationActivity.class);
                PendingIntent activity = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
                Notification notification = new NotificationCompat.Builder(this, IMPORTANT_CHANNEL_ID)
                        .setContentTitle("通知标题")
                        .setContentText("通知内容")
                        .setSmallIcon(R.drawable.wolfram)   // 设置小图标，android5之后只能用alpha图
                        .setColor(Color.parseColor("#00ff00"))
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.apple))
                        .setContentIntent(activity)  // 点击内容后跳转到
                        .setAutoCancel(true)  // 点击通知后自动取消消息
                        .build();
                notificationManager.notify(1, notification);
                break;
            case R.id.button2:
                // 这里的id需要和发通知时的id一致
                notificationManager.cancel(1);
                break;
        }
    }

    /**
     * 跳转到通知权限页面
     *
     * @param context
     */
    public static void openNotificationSettingsForApp(Context context) {
        // Links to this app's notification settings.
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // for Android 8 and above
            intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", context.getPackageName());
            intent.putExtra("app_uid", context.getApplicationInfo().uid);
        } else {
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.setData(Uri.parse("package:" + context.getPackageName()));
        }
        context.startActivity(intent);
    }

}
